package com.gragra.util;
import java.util.Arrays;
import java.util.Collection;
/**
 * this is given an string of characters on construction, subsequent calls to the apply method will generated a trimmed string, in which all those characters occurrences in the string have been surrounded by whitespace and which is otherwise identical
 * @author Christoph Teichmann
 * created Oct 28, 2012 8:25:25 PM
 * @version 0.1
 */
public class ReplaceWithSelf
{
	/**
	 * this string entries that will be surrounded by whitespace
	 */
	private final Collection<String> elements;
	/**
	 * create an instance that will surround all the characters in toReplace with whitespace
	 */
	public ReplaceWithSelf(final String toReplace)
	{
		String[] arr = toReplace.split("");
		elements = Arrays.asList(Arrays.copyOfRange(arr, 1, arr.length));
	}
	/**
	 * gives the return value as a string
	 * @param to
	 * @return
	 */
	public String apply(final String to)
	{
		return this.apply(to, true).toString().trim();
	}
	/**
	 * creates the return value as a StringBuilder, this version does not trim the output
	 * @param to
	 * @return
	 */
	public StringBuilder apply(final String to,boolean makeStringBuilder)
	{
		StringBuilder sb = new StringBuilder();
		String[] workOn = to.split("");
		for(int i=1;i<workOn.length;++i)
		{
			if(elements.contains(workOn[i]))
			{
				sb.append(" ");
				sb.append(process(workOn[i]));
				sb.append(" ");
			}
			else
			{
				sb.append(process(workOn[i]));
			}
		}
		return sb;
	}
	/**
	 * this method allows overwriting classes to change the characters in the return lines, each character is given individually
	 * @param string
	 * @return
	 */
	protected String process(String string)
	{
		return string;
	}
}